/*
     WinSockUtils.h
	 This file contains the needed functions to send/receive socket messages.

	 Date Created: 7/25/2013
	 Initial Author: Elio Decolli
	 Web Site: ecoders.weebly.com

	 Copyright (C) eCoders 2013.
*/

#ifndef UNICODE
#define UNICODE
#endif

#define WIN32_LEAN_AND_MEAN

#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>

#pragma comment(lib, "Ws2_32.lib")

#define SOCK_ERROR_WSA 0xAAA1
#define SOCK_ERROR_WINSOCK 0xAAA2

int   WinSock_Send(char* server, int port, char* msg, void* out_msg)
{
	    int iResult;
    WSADATA wsaData;

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService; 

    //int recvbuflen = DEFAULT_BUFLEN;
    char *sendbuf = msg;
    char *recvbuf = "";

    //----------------------
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
        return SOCK_ERROR_WSA;
    }

    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        WSACleanup();
        return SOCK_ERROR_WINSOCK;
    }

    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr( server );
    clientService.sin_port = htons( port );

    //----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
    if (iResult == SOCKET_ERROR) {
        closesocket(ConnectSocket);
        WSACleanup();
        return SOCK_ERROR_WINSOCK;
  }

    //----------------------
    // Send an initial buffer
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        closesocket(ConnectSocket);
        WSACleanup();
        return SOCK_ERROR_WINSOCK;
    }

    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        closesocket(ConnectSocket);
        WSACleanup();
        return SOCK_ERROR_WINSOCK;
    }

    // Receive until the peer closes the connection
        iResult = recv(ConnectSocket, recvbuf, (30*1024), 0);
        if ( iResult > 0 )
			memcpy(out_msg, recvbuf, strlen(recvbuf));


    // close the socket
    iResult = closesocket(ConnectSocket);
    if (iResult == SOCKET_ERROR) {
        WSACleanup();
        return SOCK_ERROR_WINSOCK;
    }

    WSACleanup();
    return 0;
}